package com.shuai.blog.controller;

import com.shuai.blog.common.HttpResult;
import com.shuai.blog.common.MarkdownToPlainText;
import com.shuai.blog.common.UserSessionUtils;
import com.shuai.blog.entity.ArticleInfo;
import com.shuai.blog.entity.UserInfo;
import com.shuai.blog.service.ArticleService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController {
    @Resource
    private ArticleService articleService;

    @RequestMapping("/my_list")
    public HttpResult getBlogList(HttpServletRequest request) {
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "非法请求");
        }
        List<ArticleInfo> blogList = articleService.getBlogList(userInfo.getUserId());
        for (ArticleInfo articleInfo : blogList) {
            String content = articleInfo.getContent();
            if (content.length() > 200) {
                content = content.substring(0, 200) + "...";
            }
            articleInfo.setContent(articleInfo.getContent().replaceAll("#",""));
            String convert = MarkdownToPlainText.convert(content);
            articleInfo.setContent(convert);
        }
        return HttpResult.success(blogList);
    }

    @RequestMapping("/del")
    public HttpResult deleteArt(HttpServletRequest request, Integer artId) {
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "非法请求");
        }
        if (artId == null || artId <= 0) {
            return HttpResult.fail(-2, "非法参数");
        }
        return HttpResult.success(articleService.deleteArt(userInfo.getUserId(), artId));
    }

    @RequestMapping("/getArt")
    public HttpResult getArtDetail(Integer artId) {
        if (artId == null || artId <= 0) {
            return HttpResult.fail(-1, "参数非法");
        }
        return HttpResult.success(articleService.getArtDetail(artId));
    }

    @RequestMapping("/increment")
    public HttpResult incrementVisits(Integer artId) {
        if (artId == null || artId <= 0) {
            return HttpResult.fail(-1, "非法参数");
        }
        return HttpResult.success(articleService.incrementVisits(artId));
    }

    @RequestMapping("/add_blog")
    public HttpResult addBlog(HttpServletRequest request, ArticleInfo articleInfo) {
        if (articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle())
                || !StringUtils.hasLength(articleInfo.getContent())
                || articleInfo.getArtId() == null) {
            return HttpResult.fail(-1, "非法参数");
        }
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null || userInfo.getUserId() <= 0) {
            return HttpResult.fail(-1, "非法请求");
        }
        articleInfo.setUserId(userInfo.getUserId());
        if (articleInfo.getArtId() != -1) {
            articleInfo.setState(1);
            articleInfo.setUpdateTime(LocalDateTime.now());
            return HttpResult.success(200, articleService.updateDraft(articleInfo));
        } else {
            return HttpResult.success(200, articleService.addBlog(articleInfo));
        }
    }

    @RequestMapping("/update_art")
    public HttpResult updateBlog(HttpServletRequest request, ArticleInfo articleInfo) {
        if (articleInfo == null
                || !StringUtils.hasLength(articleInfo.getContent())
                || !StringUtils.hasLength(articleInfo.getTitle())
                || articleInfo.getArtId() <= 0) {
            return HttpResult.fail(-1, "非法参数");
        }
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "非法请求");
        }
        articleInfo.setUserId(userInfo.getUserId());
        articleInfo.setUpdateTime(LocalDateTime.now());
        articleInfo.setState(1);
        return HttpResult.success(articleService.updateBlog(articleInfo));
    }

    @RequestMapping("/limit")
    public HttpResult getBlogList(Integer pageSize, Integer pageIndex) {
        //参数校验
        if (pageSize == null || pageSize <= 0 || pageIndex == null || pageIndex <= 0) {
            return HttpResult.fail(-1, "非法参数");
        }
        int offset = (pageIndex - 1) * pageSize;
        List<ArticleInfo> pageList = articleService.getPageList(pageSize, offset);
        for (ArticleInfo articleInfo : pageList) {
            if(articleInfo.getContent().length() > 300) {
                articleInfo.setContent( articleInfo.getContent().substring(0,300) + "...");
            }
        }
        int count = articleService.getCount();
        int pageCount = (int) Math.ceil(count / (pageSize * 1.0));
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("pageList", pageList);
        hashMap.put("count", pageCount);
        return HttpResult.success(hashMap);
    }

    @RequestMapping("/draft")
    public HttpResult addDraft(HttpServletRequest request, ArticleInfo articleInfo) {
        if (articleInfo == null
                || !StringUtils.hasLength(articleInfo.getContent())
                || !StringUtils.hasLength(articleInfo.getTitle())
                || articleInfo.getArtId() == null) {
            return HttpResult.fail(-1, "参数非法");
        }
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "非法请求");
        }
        articleInfo.setState(0);
        articleInfo.setUserId(userInfo.getUserId());
        if (articleInfo.getArtId() == -1) {
            articleService.addDraft(articleInfo);
        } else {
            articleInfo.setArtId(articleInfo.getArtId());
            articleInfo.setUpdateTime(LocalDateTime.now());
            articleService.updateDraft(articleInfo);
        }
        return HttpResult.success(articleInfo.getArtId());
    }

    @RequestMapping("/time_push")
    public HttpResult onTimePush(HttpServletRequest request, ArticleInfo articleInfo, String createTimeLocal) {
        if (articleInfo == null ||
                !StringUtils.hasLength(articleInfo.getContent())
                || !StringUtils.hasLength(articleInfo.getTitle())
                || createTimeLocal == null) {
            return HttpResult.fail(-1, "非法参数");
        }
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "非法请求");
        }
        String dateStr = createTimeLocal.replace("T", " ");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);
        if (localDateTime.isBefore(LocalDateTime.now())) {
            return HttpResult.fail(-1, "非法参数");
        }
        articleInfo.setCreateTime(localDateTime);
        articleInfo.setUpdateTime(localDateTime);
        articleInfo.setState(0);
        articleInfo.setUserId(userInfo.getUserId());
        //如果已经保存了要定时发布的博客草稿,那么在定时发布保存之前先删除它
        if (articleInfo.getArtId() != -1) {
            articleService.deleteDraftBeforePush(articleInfo);
        }
        return HttpResult.success(articleService.onTimePush(articleInfo));
    }

    @RequestMapping("/oper_like")
    public HttpResult operateLike(String likeState, Integer artId, HttpServletRequest request) {
        if (!StringUtils.hasLength(likeState) ||
                artId == null) {
            return HttpResult.fail(-1, "非法参数");
        }
        if (!"add".equals(likeState) && !"sub".equals(likeState)) {
            return HttpResult.fail(-1, "非法参数");
        }
        UserInfo userInfo = UserSessionUtils.getUserInfo(request);
        if (userInfo == null) {
            return HttpResult.fail(-1, "您尚未登录！");
        }
        int likeNum = 0;
        if ("add".equals(likeState)) {
            likeNum = articleService.addLikeNum(artId);
        } else {
            likeNum = articleService.subLikeNum(artId);
        }
        return HttpResult.success(likeNum);
    }
}
